package com.heima.health.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.health.dto.CheckGroupDto;
import com.heima.health.entity.PageResult;
import com.heima.health.entity.QueryPageBean;
import com.heima.health.mapper.CheckGroupMapper;
import com.heima.health.pojo.CheckGroup;
import com.heima.health.service.CheckGroupService;
import com.heima.health.service.CheckItemService;
import com.heima.health.vo.CheckGroupVO;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class CheckGroupServiceImpl extends ServiceImpl<CheckGroupMapper, CheckGroup> implements CheckGroupService {

    @Autowired
    private CheckItemService checkItemService;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Page pageData=null;
        QueryWrapper<CheckGroup> wrapper=new QueryWrapper<>();
        wrapper.eq("IS_DELETE",0);
        if (queryPageBean.getQueryString()==null){
            pageData=page(new Page<>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize()),wrapper);
        }else {
            wrapper.like("NAME",queryPageBean.getQueryString());
            pageData=page(new Page<>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize()),wrapper);
        }
        return new PageResult(pageData.getTotal(),pageData.getRecords());
    }

    @Override
    public Boolean saveUpdate(CheckGroupDto checkGroupDto) {
        Integer gid = checkGroupDto.getId();
        System.out.println((gid!=null)+"===============");
        if (gid!=null){
            //更新操作，先删除中间表的gid对应的cid
            baseMapper.deleteCidByGid(gid);
        }
        boolean flag = saveOrUpdate(checkGroupDto);
        gid=checkGroupDto.getId();
        Integer[] itemIds = checkGroupDto.getItemIds();
        if (itemIds!=null){
            for (Integer itemId : itemIds) {
                baseMapper.insertCidByGId(gid,itemId);
            }
        }
        return flag;
    }

    @Override
    public CheckGroupVO findByGid(Integer gid) {
        CheckGroupVO checkGroupVO=baseMapper.findById(gid);
        checkGroupVO.setCheckItems(checkItemService.list());
        checkGroupVO.setCheckitemIds(baseMapper.findIds(gid));
        return checkGroupVO;
    }
}
